<template>
  <el-row class="basic-box">
    <el-form :model="form" ref="form" label-width="120px">
      <el-form-item label="招商名称："
            prop="sponsorBase.title"
            :rules="[
              { required: true, message: '名称不能为空'},
            ]">
        <el-col :span="20">
          <el-input v-model="form.sponsorBase.title" placeholder="请输入招商方案名称" :maxlength="40" number-word />
        </el-col>
      </el-form-item>
      <el-form-item label="项目图片："
            prop="sponsorBase.logoUrl"
            :rules="[
              { required: true, message: '图片不能为空'},
            ]">
          <e-img-upload v-model="form.sponsorBase.logoUrl" class="logo-upload" />
          <div class="form-help">请上传赛事介绍图片用于前台，宽度不小于400px，高度不小于300px，格式为JPG，JPEG，GIF，PNG</div>
      </el-form-item>
      <el-form-item label="活动类型：" prop="sponsorBase.activeType"
            :rules="[
              { required: true, message: '活动类型不能为空'},
            ]">
        <el-col :span="20">
        <el-radio-group v-model="form.sponsorBase.activeType">
          <el-radio v-for="(item,index) in dict.activityTypes.data" :key="index" :label="item.value">{{item.label}}</el-radio>
        </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item label="比赛项目：" prop="projectList"
          :rules="[
                { required: true, message: '请选择比赛项目'},
              ]">
        <el-col :span="24">
          <el-checkbox-group v-model="form.projectList" :min="1">
            <el-checkbox v-for="(item,index) in sportType.data" :key="index" :label="item.value">{{item.label}}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-form-item>
      <el-form-item label="主办方："
          prop="sponsorOrganizationRespVO.sponsorsList"
          :rules="[
          { required: true, message: '主办方不能为空'},
          Object.assign({}, validator.rule.orgArray,{message: '单位名称字符应在2~30个字符'})
        ]">
        <el-col :span="12">
          <e-input-group :minlength="2" :maxlength="30" :max-item="5" placeholder="请输入主办单位名称" :max="6" v-model="form.sponsorOrganizationRespVO.sponsorsList"></e-input-group>
        </el-col>
      </el-form-item>
      <el-form-item label="承办方："
          prop="sponsorOrganizationRespVO.organizersList"
          :rules="[
          { required: true, message: '承办方不能为空'},
          Object.assign({}, validator.rule.orgArray,{message: '单位名称字符应在2~30个字符'})
        ]">
        <el-col :span="12">
         <e-input-group :minlength="2" :maxlength="30" :max-item="5" placeholder="请输入承办单位名称" :max="6" v-model="form.sponsorOrganizationRespVO.organizersList"></e-input-group>
        </el-col>
      </el-form-item>
      <el-form-item label="级别：" prop="sponsorBase.activeLevel" class="dividing-line"
        :rules="{ required: true, message: '请选择级别'}">
        <el-col :span="24">
          <el-radio-group v-model="form.sponsorBase.activeLevel">
            <el-radio v-for="(item,index) in dict.levelTypes.data" :key="index" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item label="活动规模：" prop="sponsorBase.activeScale"
            :rules="[
              { required: true, message: '活动规模不能为空'},
            ]">
        <el-col :span="20">
          <el-radio-group v-model="form.sponsorBase.activeScale">
            <el-radio v-for="(item,index) in dict.activeScales.data" :key="index" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item label-width="10px" class="address-error" prop="addressTime" :rules="addressRules">
        <el-row :span="24" class="address-box">
          <address-time v-model="form.addressTime" :max-item="form.sponsorBase.activeScale === 1 ? 1 : 10"></address-time>
        </el-row>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="参加人数：" prop="sponsorBase.joinNumber"
            :rules="[
              { required: true, message: '参加人数不能为空'},
              Object.assign({}, validator.rule.isIntadd,{message: '输入格式不正确，名额为正整数'}),
              Object.assign({}, validator.rule.peopreRange,{message: '不能超出0~100000的范围'})
              ]">
            <el-col :span="19">
              <el-input v-model="form.sponsorBase.joinNumber" placeholder="请输入参加人数"></el-input>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="现场观众：" prop="sponsorBase.audience"
            :rules="[
              { required: true, message: '观众人数不能为空'},
              Object.assign({}, validator.rule.isIntadd,{message: '输入格式不正确，名额为正整数'}),
              Object.assign({}, validator.rule.peopreRange,{message: '不能超出0~100000的范围'})
              ]">
            <el-col :span="19">
              <el-input v-model="form.sponsorBase.audience" :max="10" placeholder="请输入现场观众人数"></el-input>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="dividing-line divider"></el-row>
      <el-form-item label="招商截止：" prop="sponsorBase.endType"
        :rules="[
          { required: true, message: '时间不能为空'}
        ]">
        <el-col :span="24">
          <el-radio-group v-model="form.sponsorBase.endType">
            <el-radio v-for="(item,index) in dict.cutoff.data" :key="index" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item label="联系人：" prop="sponsorBase.contactPerson"
        :rules="[
          { required: true, message: '联系人不能为空'},
          { min: 2, max: 20, message: '请输入符合规范的昵称'}
          ]">
        <el-col :span="8">
          <el-input v-model="form.sponsorBase.contactPerson" placeholder="请输入联系人" number-word />
        </el-col>
      </el-form-item>
      <el-form-item label="联系电话：" prop="sponsorBase.contactPhone"
        :rules="[
          { required: true, message: '联系电话不能为空'},
          Object.assign({}, validator.rule.mobile,{message: '手机号码格式不正确'})
          ]">
        <el-col :span="8">
          <el-input v-model="form.sponsorBase.contactPhone" placeholder="请输入联系电话" number-word />
        </el-col>
      </el-form-item>
      <div class="button-box">
        <el-button type="primary" @click="next()" v-if="!id">下一步</el-button>
        <el-button type="primary" :loading="loading" native-type="submit" v-if="id" @click="save()">保存</el-button>
      </div>
    </el-form>
  </el-row>
</template>
<script>
import { mapGetters } from 'vuex'
import EImgUpload from '@e-ui/ImgUpload'
import validator from '../../../utils/validator'
import EInputGroup from '@e-ui/InputGroup'
import AddressTime from './components/AddressTime'
import filters from '../../../filters'
import api from 'api/merchants'
export default {
  props: {
    activeChange: {
      type: Function
    }
  },
  components: {
    EImgUpload,
    EInputGroup,
    AddressTime
  },
  computed: {
    ...mapGetters({
      dict: 'merchants_dict',
      form: 'merchants_form'
    }),
    dateTime: {
      set (value) {
        this.form.activityTime = value && value[0] ? value : ''
      },
      get () {
        return this.form.activityTime
      }
    }
  },
  created () {
    this.activeChange(1)
    this.sportTypeFn()
  },
  data () {
    var validateAddress = (rule, value, callback) => {
      let message = '活动地点和活动时间不能为空'
      let result = value.every(item => {
        return !!item.address && item.activityTime.length > 0 && item.areas.length > 0
      })
      if (!result || value.length === 0) {
        callback(new Error(message))
      } else {
        callback()
      }
    }
    return {
      validator,
      loading: false,
      id: this.$route.params.id,
      sportType: [],
      addressRules: [
        {validator: validateAddress}
      ],
      baseData: { // 分模块保存，
        sponsorAreaList: [],
        sponsorBase: {
          activeLevel: 1, // 活动级别
          activeScale: 1, // 活动规模
          activeType: 1, // 活动类型
          audience: '', // 现场观众
          contactPerson: '', // 联系人
          contactPhone: '', // 联系电话
          endType: 1, // 招商截止
          joinNumber: '', // 参加人数
          logoUrl: '', // 招商logo图片
          title: '' // 招商名称
        },
        sponsorOrganizationRespVO: {
          organizersList: [], // 承办方
          sponsorsList: [] // 主办方
        },
        sponsorProjectList: [] // 项目类型
      }
    }
  },
  methods: {
    save () {
      let formdata = Object.assign({}, this.form) // 复制一个新的数据对象
      let basedata = Object.assign({}, this.baseData) // 复制一个新的数据对象
      for (let attr in basedata) { // 将返回来的数据做跟我的form里面的数据要一一对应进来，只拿form所需要的数据
        basedata[attr] = formdata[attr]
      }
      formdata.sponsorProjectList.forEach((item) => {
        delete item.projectName
      })
      basedata.sponsorAreaList = formdata.addressTime.map(function (item) { // 将更新的数据form转成提交的格式
        return {
          city: item.areas[1], // 市
          detailsAddress: item.address, // 详细地址
          endTime: filters.FormatDate(item.activityTime[1], 'yyyy-MM-dd'), // 时间
          province: item.areas[0], // 省
          startTime: filters.FormatDate(item.activityTime[0], 'yyyy-MM-dd')
        }
      })
      basedata.sponsorProjectList = this.form.projectList.map(function (item) { // 将我表单的比赛项目转换成后台接受的格式
        return {
          projectType: item
        }
      })
      basedata.id = this.id
      this.$refs['form'].validate((valid) => {
        if (valid) {
          api.base_update(JSON.stringify(basedata), {context: this, successMsg: 'none'}).then((json) => {
            this.$message.success('修改成功')
          }).catch((json) => {
            if (json.result === '4002') {
              this.$message.warning('活动开始时间须重新设置！')
            } else {
              this.$message.warning('服务器繁忙，请稍后再试！')
            }
          })
        } else {
          this.$message.warning('请输入完整信息')
          return false
        }
      })
    },
    next () {
      this.$store.commit('SPONSOR_MERCHANTS_COOKIES', { // 点击下一步的时候，将当前页的数据保存到cookies
        type: true
      })
      this.$refs['form'].validate((valid) => {
        if (valid) { // 检验通过后，才可以到下一步
          this.$router.push({path: '/sponsor/merchants/set'})
        } else {
          this.$message.warning('请输入完整信息')
          return false
        }
      })
    },
    sportTypeFn () { // 品牌类型下拉的数据
      api.sport_type({
      }).then(res => {
        this.sportType = res
      })
    }
  }
}
</script>
<style lang="scss">
.basic-box{
  margin-top:60px;
  .button-box{
    margin-top: 100px;
  }
  .address-box{
    margin-top: 10px;
  }
  .el-select{
    width:235px;
  }
  .address-error{
    position:relative;
    .el-form-item__error{
      position:absolute;
      top:-12px;
    }
  }
  .dividing-line{
     margin:30px 0px 50px;
  }
  .form-style{
    border:1px #ccc solid;
    margin:20px;
    border-radius:4px;
    padding:20px 0px;
  }
  .img-upload{
    width:160px;
    height:90px;
  }
}
</style>
